#!/usr/bin/env python
#coding=utf-8

import tornado.httpserver
import tornado.ioloop


class HttpServer(object):
    def __init__(self, port, callbackRecv):
        self._port = port
        self._callbackRecv = callbackRecv
    
    def _on_recv(self, request):
        rtval = self._callbackRecv(request.body)
        s = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Length: %d\r\n\r\n%s" % (len(rtval), rtval)
        request.connection.write(bytes(s, encoding="utf-8"))
        request.connection.finish()
        
    def start(self):
        http_server = tornado.httpserver.HTTPServer(self._on_recv)
        http_server.bind(self._port)
        http_server.start()
        
    def ioloop(self):  
        #启动事件循环，开始监听网络事件，主要是socket的读和写
        tornado.ioloop.IOLoop.instance().start()
        
        
